package terra.slick;

import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.newdawn.slick.AppletGameContainer;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;

import terra.Game;
import terra.Loader;
import terra.managers.ResourceManager;
import terra.network.Client;
import terra.network.packet.client.RequestLogIn;
import terra.network.packet.server.ChunkInfo;
import terra.twl.BasicTWLGameState;
import terra.twl.RootPane;
import de.matthiasmann.twl.Button;
import de.matthiasmann.twl.EditField;
import de.matthiasmann.twl.FPSCounter;
import de.matthiasmann.twl.Label;


public class MenuState extends BasicTWLGameState implements ChannelFutureListener {

	private static MenuState instance;
	public boolean enterGame = false;
	public boolean enteredGame = false;

	@Override
	public void init(GameContainer arg0, StateBasedGame arg1)throws SlickException{
		ResourceManager.loadResources(Game.class.getResourceAsStream("resources.xml"));
		if (arg0 instanceof AppletGameContainer.Container){
			Loader.init();
			Game.app = arg0;
			Game.app.setTargetFrameRate(60);
			Game.app.setShowFPS(false);
			Game.app.setAlwaysRender(true);
			Game.app.setUpdateOnlyWhenVisible(true);
		}
		System.out.println("CHUNK SIZE: "+ ChunkInfo.size);
	}

	@Override
	public void update(GameContainer arg0, StateBasedGame arg1, int arg2)
			throws SlickException {
		if (enterGame){
			if (!enteredGame){
				Game.instance.enterState(1, new FadeOutTransition(Color.black,1000), new FadeInTransition(Color.black,1000));
				enteredGame = true;
			}
		}
	}

	@Override
	public int getID() {
		return 0;
	}

	public static MenuState getInstance() {
		if (instance == null)
			return instance = new MenuState();
		return instance;
	}

	protected void requestLogIn() {
		if (loginTextField.getText().length() > 3 && passwordTextField.getText().length() > 3){
			Loader.handler.send(new RequestLogIn(loginTextField.getText(), passwordTextField.getText()));
		}
	}
	
	FPSCounter fpsCounter;
	EditField loginTextField,passwordTextField;
	Button loginButton;
	public Label errorLabel;
	
	@Override
    protected void layoutRootPane() {
		for(int i = 0; i < getRootPane().getNumChildren();i++)
			getRootPane().getChild(i).adjustSize();
    }
	
    @Override
    protected RootPane createRootPane() {
    	RootPane rootPane = super.createRootPane();
        fpsCounter = new FPSCounter(3,1);
        errorLabel = new Label();
        loginTextField = new EditField();
        passwordTextField = new EditField();
        loginButton = new Button("Log in");
        loginButton.addCallback(new Runnable(){
			@Override
			public void run() {
				if (Loader.handler == null) {
					ChannelFuture future = Client.getInstance().connect();
					if(future != null)
						future.addListener(MenuState.this);
				} else if (!enterGame){
					requestLogIn();
				}
			}});
        
        fpsCounter.setPosition(10, 10);
        loginTextField.setPosition(10, 30);
        loginTextField.setMaxTextLength(16);
        loginTextField.setFocusKeyEnabled(true);
        passwordTextField.setPosition(10, 50);
        passwordTextField.setMaxTextLength(16);
        passwordTextField.setFocusKeyEnabled(true);
        passwordTextField.setPasswordMasking(true);
        errorLabel.setPosition(10, 110);
        errorLabel.setSize(150, 14);
        errorLabel.setText("");
        loginButton.setPosition(25, 75);
        loginButton.setFocusKeyEnabled(true);
        rootPane.add(fpsCounter);
        rootPane.add(loginTextField);
        rootPane.add(passwordTextField);
        rootPane.add(loginButton);
        rootPane.add(errorLabel);
        rootPane.setFocusKeyEnabled(true);
        return rootPane;
    }

	@Override
	public void operationComplete(ChannelFuture future) throws Exception {
		System.out.println("operationComplete" + future.getCause());
		if (future.isSuccess())
			requestLogIn();
	}

	@Override
	public void render(GameContainer arg0, StateBasedGame arg1, Graphics arg2)
			throws SlickException {
	}
	
	@Override
	public void leave(GameContainer container, StateBasedGame game) throws SlickException	{
		super.leave(container, game);
		getRootPane().destroy();
	}
	
	@Override
	public void enter(GameContainer container, StateBasedGame game) throws SlickException {
		super.enter(container, game);
		enterGame = false;
		getRootPane().reapplyTheme();
		Client.getInstance().connect();
	}
	
}
